package com.hxzy.config.security;

import cn.hutool.core.util.StrUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.service.system.impl.TokenService;
import com.hxzy.util.ServletUtil;
import com.hxzy.vo.AdminLoginVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 没有权限（401，403）这些情况要输出的json格式
 */
@Log4j2
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {


    @Autowired
    private TokenService tokenService;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
       log.error(authException);
        String msg = StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());

        //取得令牌
        String jwtToken=request.getHeader("Authorization");

        R r=null;

        //如果有令牌，验证令牌有效性
        if(StrUtil.isNotBlank(jwtToken)){
            AdminLoginVO adminLoginVO = this.tokenService.validatorToken(jwtToken);

            if(adminLoginVO!=null){
                //有效的
                 r=R.build(AckCode.NO_PERMISSION_TO_ACCESS);
                r.setMsg(msg);
            }else{
                //令牌无效
                r=R.build(AckCode.TOKEN_FAIL);
            }
        }else{
            r=R.build(AckCode.SYSTEM_TOKEN_FAIL);
        }

        ServletUtil.outJson(response,r);
    }
}
